<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { ref, unref, reactive, watch, nextTick } from 'vue'
import { ElTag, ElMessage } from 'element-plus'
import {
  getDictItemListApi,
  saveDictItemApi,
  updateDictItemApi,
  deleteDictItemApi
} from '@/api/dict'
import type { DepartmentUserItem } from '@/api/department/types'
import { useTable } from '@/hooks/web/useTable'
import { Search } from '@/components/Search'
import Write from './components/Write.vue'
import { Dialog } from '@/components/Dialog'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'

const props = defineProps({
  parentsRow: {
    type: Object,
    default: () => {}
  }
})

watch(
  () => props.parentsRow,
  async (parentsRow) => {
    if (!parentsRow) return
    await nextTick()
    getList()
  },
  {
    // deep: true,
    immediate: true
  }
)

const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await getDictItemListApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      dictType: props.parentsRow.dictType,
      ...unref(searchParams)
    })
    return {
      list: res.data.records || [],
      total: res.data.total || 0
    }
  },
  fetchDelApi: async () => {
    const res = await deleteDictItemApi(unref(dictCode))
    return !!res
  },
  immediate: false
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'index',
    label: t('userDemo.index'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      type: 'index'
    }
  },
  {
    field: 'dictLabel',
    label: '名称'
  },
  {
    field: 'dictValue',
    label: '数据值',
    search: {
      hidden: true
    }
  },
  {
    field: 'remark',
    label: '描述'
  },
  {
    field: 'dictSort',
    label: '排序'
  },
  {
    field: 'status',
    label: '状态',
    search: {
      hidden: true
    },
    form: {
      component: 'Select',
      componentProps: {
        options: [
          {
            label: t('userDemo.disable'),
            value: 1
          },
          {
            label: t('userDemo.enable'),
            value: 0
          }
        ]
      }
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <ElTag type={data.row.status === 1 ? 'danger' : 'success'}>
                {data.row.status === 0 ? t('userDemo.enable') : t('userDemo.disable')}
              </ElTag>
            </>
          )
        }
      }
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      width: 240,
      slots: {
        default: (data: any) => {
          const row = data.row as DepartmentUserItem
          return (
            <>
              <BaseButton type="primary" onClick={() => action(row, 'edit')}>
                {t('exampleDemo.edit')}
              </BaseButton>
              <BaseButton type="danger" onClick={() => delData(row)}>
                {t('exampleDemo.del')}
              </BaseButton>
            </>
          )
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const searchParams = ref({})
const setSearchParams = (params: any) => {
  currentPage.value = 1
  searchParams.value = params
  getList()
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<any>()
const actionType = ref('')

const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = undefined
  dialogVisible.value = true
  actionType.value = ''
}

const delLoading = ref(false)
const ids = ref<string[]>([])
const dictCode = ref('')

const delData = async (row: any) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row
    ? [row.dictCode]
    : elTableExpose?.getSelectionRows().map((v: DepartmentUserItem) => v.id) || []
  dictCode.value = row.dictCode
  delLoading.value = true

  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const action = (row: DepartmentUserItem, type: string) => {
  dialogTitle.value = t('exampleDemo.edit')
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    try {
      if (formData.dictCode) {
        await updateDictItemApi(formData)
      } else {
        formData.dictType = props.parentsRow.dictType
        await saveDictItemApi(formData)
      }
    } catch (error) {
      console.log(error)
      ElMessage.success('保存接口异常')
    } finally {
      // currentPage.value = 1
      saveLoading.value = false
      dialogVisible.value = false
      ElMessage.success('保存成功')
      getList()
    }
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @reset="setSearchParams" @search="setSearchParams" />

    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</BaseButton>
    </div>
    <Table
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      @register="tableRegister"
      :pagination="{
        total
      }"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write ref="writeRef" :form-schema="allSchemas.formSchema" :current-row="currentRow" />
    <template #footer>
      <BaseButton type="primary" :loading="saveLoading" @click="save">
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
